package obecto.task
{
	import flash.events.EventDispatcher;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import obecto.event.TaskEvent;
	import obecto.event.TaskEventKind;

	[Event(name="start", type="obecto.event.TaskEvent")]
	[Event(name="complete", type="obecto.event.TaskEvent")]

	public class BaseTask extends EventDispatcher implements ITask
	{
		protected var _running : Boolean = false;
		
		[Bindable] public var delay : Number;
		
		protected var delayId : uint;
		
		public function BaseTask()
		{
			super();
		}

		public function start() : void
		{
			if(running == false)
			{
				_running = true;
				
				if (isNaN(delay) || delay == 0)
				{
					startActual();
				}
				else
				{
					delayId = setTimeout(startWithDelay, delay * 1000);
				}
				
				dispatchEvent(new TaskEvent(TaskEvent.START));
			}
		}
		
		protected function startWithDelay() : void 
		{
			startActual();
			clearTimeout(delayId);
			delayId = NaN;
		}
		
		virtual protected function startActual() : void
		{
		}
		
		protected function complete() : void
		{
			_running = false;
			
			dispatchEvent(new TaskEvent(TaskEvent.COMPLETE, TaskEventKind.END));
		}
		
		public function get running() : Boolean
		{
			return _running;
		}		
	}
}